package cn.com.netedge.iot.frontend.biz.utils;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson2.JSON;
import cn.com.netedge.iot.common.constants.CacheKeyConstants;
import cn.com.netedge.iot.common.dataobject.DeviceRunningInfo;
import cn.com.netedge.iot.common.utils.DateUtil;
import cn.com.netedge.iot.common.utils.RedisUtil;
import cn.com.netedge.iot.common.utils.StringUtil;

public class FeBizCacheUtil {
    private static Logger logger = LoggerFactory.getLogger(FeBizCacheUtil.class);

    //任务采用队列（先进先出）
    public static boolean isHavingTask(String deviceNumber, int deviceType) {
        String rtuTaskKey = CacheKeyConstants.KEY_DEVICE_TASK + deviceNumber + "_" + deviceType;
        long length = RedisUtil.llen(rtuTaskKey);
        if (length > 0) {
            return true;
        }
        return false;
    }

    public static DeviceRunningInfo getDeviceRunningInfo(String deviceNumber, int deviceType) {
        String key = CacheKeyConstants.KEY_DEVICE_RUNNING + deviceNumber + "_" + deviceType;
        String value = RedisUtil.get(key);
        if(StringUtil.isEmpty(value)) {
            return null;
        }
        return JSON.parseObject(value, DeviceRunningInfo.class);
    }

    public static synchronized void setTopTask(String deviceNumber, int deviceType, String cmdId) {
        String deviceTaskKey = CacheKeyConstants.KEY_DEVICE_TASK + deviceNumber + "_" + deviceType;
        RedisUtil.rightPush(deviceTaskKey, cmdId);
    }

    //任务采用队列（先进先出）
    public static synchronized void popTopTask(String deviceNumber, int deviceType, String cmdId) {
        String deviceTaskKey = CacheKeyConstants.KEY_DEVICE_TASK + deviceNumber + "_" + deviceType;
        long size = RedisUtil.llen(deviceTaskKey);
        if (size == 0) {
            logger.info("{} taskList is empty!", deviceTaskKey);
            return ;
        }
        List<String> taskList = RedisUtil.range(deviceTaskKey, 0, Integer.MAX_VALUE);
        for (String task : taskList) {
            int index = task.lastIndexOf(":");
            if(index == -1) {
                continue;
            }
            String tail = task.substring(index + 1);
            tail = tail.substring(0,14);
            Date taskTime = DateUtil.StrToDate(tail, DateUtil.TIME_LONG_14);
            //超过2分钟则放弃
            if ((System.currentTimeMillis() - taskTime.getTime()) >= 2 * 60 * 1000) {
                RedisUtil.rightPop(deviceTaskKey);
                continue;
            } 
            if(cmdId.equals(task)) {
                RedisUtil.rightPop(deviceTaskKey);
                return ;
            }
        }
    }

}
